const fileRegex = /@codemirror/
const allowLanguages = [
  'C',
  'C++',
  'CSS',
  'Go',
  'HTML',
  'Java',
  'Kotlin',
  'JavaScript',
  'JSON',
  'JSX',
  'LESS',
  'Markdown',
  'MySQL',
  'PHP',
  'PostgreSQL',
  'Python',
  'Rust',
  'Ruby',
  'Sass',
  'SCSS',
  'SQL',
  'TSX',
  'TypeScript',
  'XML',
  'YAML',
  'CMake',
  'Vue',
  'VBScript',
  'Shell',
  'PowerShell',
  'Angular Template',
]

// ["C","C++","CQL","CSS","Go","HTML","Java","JavaScript","JSON","JSX","LESS","Liquid","MariaDB SQL","Markdown","MS SQL","MySQL","PHP","PLSQL","PostgreSQL",
//   "Python","Rust","Sass","SCSS","SQL","SQLite","TSX","TypeScript","WebAssembly","XML","YAML","APL",
//   "PGP","ASN.1","Asterisk","Brainfuck","Cobol","C#","Clojure","ClojureScript","Closure Stylesheets (GSS)",
//   "CMake","CoffeeScript","Common Lisp","Cypher","Cython","Crystal","D","Dart","diff","Dockerfile","DTD","Dylan","EBNF",
//   "ECL","edn","Eiffel","Elm","Erlang","Esper","Factor","FCL","Forth","Fortran","F#","Gas","Gherkin","Groovy","Haskell",
//   "Haxe","HXML","HTTP","IDL","JSON-LD","Jinja2","Julia","Kotlin","LiveScript","Lua","mIRC","Mathematica",
//   "Modelica","MUMPS","Mbox","Nginx","NSIS","NTriples","Objective-C","Objective-C++","OCaml","Octave",
//   "Oz","Pascal","Perl","Pig","PowerShell","Properties files","ProtoBuf","Pug","Puppet","Q",
//   "R","RPM Changes","RPM Spec","Ruby","SAS","Scala","Scheme","Shell","Sieve","Smalltalk","Solr","SML","SPARQL","Spreadsheet",
//   "Squirrel","Stylus","Swift","sTeX","LaTeX","SystemVerilog","Tcl","Textile","TiddlyWiki","Tiki wiki",
//   "TOML","Troff","TTCN","TTCN_CFG","Turtle","Web IDL","VB.NET","VBScript","Velocity","Verilog",
//   "VHDL","XQuery","Yacas","Z80","MscGen","Xù","MsGenny","Vue","Angular Template"]
// const match = /@codemirror\+(.*?)@/.exec(id);

export default function Codemirror() {
  return {
    name: 'transform-codemirror',
    transform(code: string, id: string) {
      if (fileRegex.test(id) && id.includes('language-data')) {
        const regex = /var\slanguages\s=\s\[(\s+.*)+];/
        const match = regex.exec(code)
        if (match) {
          const matchArr = match[0].split('LanguageDescription\.of')
          matchArr.forEach((value: string, index: number) => {
            if (index > 0) {
              const nameMatch = /name:\s"(.*)"/.exec(value)
              if (nameMatch) {
                if (!allowLanguages.includes(nameMatch[1])) {
                  code = code.replace(`LanguageDescription\.of${value}`, '')
                }
              }
            }
          })
        }
        return {
          code,
          map: null,
        }
      }
    },
  }
}
